<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { CollapseModelValue } from 'element-plus'
import { dayjs } from 'element-plus'
import DialogView from 'components/DialogView.vue'
import { retrieveScripts, fetchScript } from 'src/api/scripts'
import { retrieveDictionarySubset } from 'src/api/dictionaries'
import type { Script, Dictionary } from 'src/types'
import { Icon } from '@iconify/vue'
import { groupByType } from 'src/utils'


const loading = ref<boolean>(false)
const rowLoading = ref<boolean>(false)

const datas = ref<Array<Script>>([])
const scriptTypeOptions = ref<Array<Dictionary>>([])

const visible = ref<boolean>(false)
const activeNames = ref(['1'])

const initialValues: Script = {
  id: undefined,
  name: '',
  icon: '',
  version: '',
  content: '',
  description: ''
}
const row = ref<Script>({ ...initialValues })

/**
 * 加载列表
 */
async function load() {
  loading.value = true
  retrieveScripts().then(res => {
    datas.value = res.data
  }).finally(() => { loading.value = false })
}

async function loadScriptType() {
  retrieveDictionarySubset(68).then(res => {
    scriptTypeOptions.value = res.data
  })
}
/**
 * 加载
 * @param id 主键
 */
async function loadOne(id: number) {
  row.value = { ...initialValues }
  rowLoading.value = true
  fetchScript(id).then(res => {
    row.value = res.data
  }).finally(() => { rowLoading.value = false })
}

onMounted(() => {
  load()
  loadScriptType()
})

function handleChange(val: CollapseModelValue) {
  console.log(val)
}

/**
 * 详情
 * @param id 主键
 */
function showRow(id: number | undefined) {
  visible.value = true
  if (id) {
    loadOne(id)
  }
}
</script>

<template>
  <ElSpace size="large" fill class="w-full">
    <ElCard shadow="never">
      <ElRow :gutter="20" justify="space-between">
        <ElCol :span="16" class="text-left">
          <ElButton title="create" type="primary">
            <Icon icon="material-symbols:add-rounded" width="18" height="18" />{{ $t('create') }}
          </ElButton>
          <ElButton title="config" type="success" plain @click="visible = true">
            <Icon icon="material-symbols:rule-settings-rounded" width="18" height="18" />{{ $t('config') }}
          </ElButton>
        </ElCol>

        <ElCol :span="8" class="text-right">
          <ElTooltip class="box-item" effect="dark" :content="$t('refresh')" placement="top">
            <ElButton title="refresh" type="primary" plain circle @click="load">
              <Icon icon="material-symbols:refresh-rounded" width="18" height="18" />
            </ElButton>
          </ElTooltip>
        </ElCol>
      </ElRow>
    </ElCard>

    <ElCard shadow="never">
      <ElCollapse v-if="datas && datas.length > 0" v-model="activeNames" @change="handleChange">
        <ElCollapseItem v-for="(items, group) in groupByType(datas, scriptTypeOptions, 'type')" :key="group"
          :title="String(group)" :name="group">
          <template #title>
            <Icon icon="material-symbols:database-outline w-6 h-6" />
            <span class="text-lg">{{ group }}</span>
          </template>
          <ElRow :gutter="16">
            <ElCol :span="6" v-for="item in items" :key="item.id" class="mb-4">
              <ElCard shadow="hover" class="text-center cursor-pointer" @click="showRow(item.id)">
                <ElImage :src="item.icon" class="w-12 h-12" />
                <div>
                  <p class="my-1 text-lg text-[var(--el-text-color-regular)]">{{ item.name }}: {{ item.version }}</p>
                  <p class="my-1 text-sm text-[var(--el-text-color-secondary)]">{{ item.description }}</p>
                  <p class="my-1 text-xs text-[var(--el-text-color-secondary)]">
                    Updated Time: {{ dayjs(item.lastModifiedDate).format('YYYY-MM-DD HH:mm') }}
                  </p>
                </div>
              </ElCard>
            </ElCol>
          </ElRow>
        </ElCollapseItem>
      </ElCollapse>

      <ElEmpty v-else :image-size="300" />
    </ElCard>
  </ElSpace>

  <DialogView v-model="visible" show-close :title="$t('detail')">
    <p class="my-1 text-lg text-[var(--el-text-color-regular)]">{{ row.name }}: {{ row.version }}</p>
    <CodeRender :content="row.content" />
  </DialogView>
</template>
